import os
from google.appengine.ext.webapp import template
import cgi
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
import datetime

class Blog(db.Model):
    title = db.StringProperty()
    author = db.UserProperty()
    content = db.StringProperty(multiline=True)
    data = db.DateTimeProperty(auto_now_add=True)

class List(webapp.RequestHandler):
    def get (self):
        blogs_query = Blog.all().order('-data')
        blogs = blogs_query.fetch()

        template_values = {
            'blogs': blogs,
        }

        path = os.path.join(os.path.dirname(__file__), 'static/blog.html')
        self.response.out.write(template.render(path, template_values))

class Post(webapp.RequestHandler):
    def post (self):
        blog = Blog()
        if users.get_current_user():
            blog.author = users.get_current_user()

        title = self.request.get('title')
        content = self.request.get('content')
        if content and title:
            blog.content = content
            blog.title = title
            blog.put()
            self.redirect('/blog')
        self.redirect('/error')

application = webapp.WSGIApplication(['/', List], debug=True)
def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
